<template>
	<div id="customize_report">
		<el-card>
			<el-form :inline="true" class="flexRow" ref="searchFormRef" :model="queryParams">
				<el-form-item v-for="(SearchParamItem, idx) in filterDefCfg" :key="'select-' + idx" :label="SearchParamItem.Label">
					<component
						:ref="(el: any) => setRefInfo(el, 'searchParams_input' + idx)"
						:is="getComponent(SearchParamItem.InputType)"
						:FieldItem="SearchParamItem"
						:filterIdx="idx"
						v-model="queryParams[SearchParamItem.FieldName]"
						located="Filter"
					/>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handlerSearchBtn">查询</el-button>
					<el-button @click="handlerResetBtn">清空</el-button>
					<el-button v-if="ReportDefData?.IsExport === '1'" type="success" @click="handlerExportExcelBtn">导出</el-button>
				</el-form-item>
			</el-form>
		</el-card>
		<el-divider />
		<el-table :data="tableData.data" id="mytable" style="width: 100%" show-summary :summary-method="getSummaries">
			<el-table-column
				v-for="item in mainGrpFieldCfg"
				:key="item.FieldName"
				:prop="item.FieldName"
				:label="item.ViewName"
				fixed
				align="center"
				:width="item.ShowColWidth"
			/>
			<!-- <el-table-column
				v-for="item in otherFields"
				:key="item.value"
				:prop="item.value"
				:label="item.name"
				fixed
				align="center"
				:width="item.ShowColWidth"
			/> -->
			<el-table-column
				v-for="item in levelDataValidArray"
				:key="item.FieldLevelName"
				:prop="item.FieldLevelName"
				:label="item.ViewName"
				:width="item.ShowColWidth"
				align="center"
			>
				<template v-if="item.Childs && item.Childs.length">
					<el-table-column
						v-for="item2 in item.Childs"
						:key="item2.FieldLevelName"
						:prop="item2.FieldLevelName"
						:label="item2.ViewName"
						:width="item2.ShowColWidth"
						align="center"
					>
						<template v-if="item2.Childs && item2.Childs.length">
							<el-table-column
								v-for="item3 in item2.Childs"
								:key="item3.FieldLevelName"
								:prop="item3.FieldLevelName"
								:label="item3.ViewName"
								:width="item3.ShowColWidth"
								align="center"
							/>
						</template>
					</el-table-column>
				</template>
			</el-table-column>
			<el-table-column v-if="ReportDefData?.IsRowTotal === '1'" label="总计" fixed="right" align="center" width="80" key="RecordTotal">
				<template #default="scope">{{ scope.row.RecordTotal }}</template>
			</el-table-column>
		</el-table>
		<div v-if="ReportDefData?.IsPaging === '1'" class="pagination">
			<el-pagination
				background
				:layout="pageConfig.layout"
				:total="pageConfig.total"
				v-model:current-page="pageConfig.currentPage"
				:page-sizes="pageConfig.sizes"
				:page-size="pageConfig.pagesize"
				@size-change="handleSizeChange"
				@update:current-page="handleCurrentChange"
			/>
		</div>
	</div>
</template>
<script lang="ts" setup name="customize_report">
import { useRouter } from 'vue-router';
import { getReportID, queryReportConfigAndFieldDef, parseTableHeadDef, queryGroupData, handlerPagination } from './hooks/customize_report';
import { FieldDataValidDefine } from './interface/index';
import { getComponent } from '/@/utils/componentFactory';
import { reportExportExcel } from './hooks/report_exprot_excel';

const router = useRouter();

const ReportID = getReportID(router);
const { ReportDefData, ReportFieldData, filterDefCfg } = await queryReportConfigAndFieldDef(ReportID.value);
console.log('queryReportConfigAndFieldDef', { ReportDefData, ReportFieldData, filterDefCfg });

// 生成表头数据
const { mainGrpFieldCfg, levelNumber, levelDataValidArray, groupsFields, mapFieldDataValid, otherFields } = parseTableHeadDef(
	ReportDefData!,
	ReportFieldData
);
console.log('生成表头数据', { mainGrpFieldCfg, otherFields, levelDataValidArray, mapFieldDataValid });
const { tableData, totalSize } = queryGroupData(ReportDefData?.GroupFieldCfg, mainGrpFieldCfg, groupsFields, mapFieldDataValid, levelDataValidArray);
console.log('tableData', tableData);

// 列合计
const getSummaries = (param: any) => {
	const { data, columns } = param;
	const sums: any[] = [];
	let startIndex = 0;
	if (mainGrpFieldCfg && mainGrpFieldCfg.length > 0) {
		startIndex = mainGrpFieldCfg.length - 1;
		sums[mainGrpFieldCfg.length - 1] = '总计';
		for (let i = mainGrpFieldCfg.length - 2; i >= 0; i--) {
			sums[i] = '';
		}
	}
	for (let index = startIndex; index < columns.length; index++) {
		param.columns[columns.length - 1].property = 'RecordTotal';
		const fieldDataValid: FieldDataValidDefine | undefined = mapFieldDataValid.get(columns[index].property);
		if ((fieldDataValid && fieldDataValid.NeedSum) || columns[index].property === 'RecordTotal') {
			const values = data.map((item: any) => {
				if ((fieldDataValid && fieldDataValid.NeedSum) || columns[index].property === 'RecordTotal') {
					return Number(item[columns[index].property]);
				} else {
					return 0;
				}
			});
			if (!values.every((value: any) => isNaN(value))) {
				sums[index] = values.reduce((prev: any, curr: any) => {
					const value = Number(curr);
					if (!isNaN(value)) {
						return prev + curr;
					} else {
						return prev;
					}
				}, 0);
				sums[index] += ' ';
			} else {
				sums[index] = '0';
			}
		} else {
			sums[index] = ' ';
		}
	}
	if (mainGrpFieldCfg && mainGrpFieldCfg.length > 0) {
		startIndex = mainGrpFieldCfg.length - 1;
		sums[mainGrpFieldCfg.length - 1] = '总计';
		for (let i = mainGrpFieldCfg.length - 2; i >= 0; i--) {
			sums[i] = '';
		}
	}

	// console.log('getSummaries sums: ', sums);
	return sums;
};

// 分页器
const { pageConfig, handleSizeChange, handleCurrentChange } = handlerPagination(
	ReportDefData!,
	tableData,
	groupsFields,
	mapFieldDataValid,
	levelDataValidArray
);
watch(
	() => totalSize.value,
	() => {
		pageConfig.total = totalSize.value;
		console.log('totalSize', totalSize.value);
	}
);

const queryParams = reactive<Record<string, any>>({});
const refInfo: Record<string, any> = ref({});
const setRefInfo = (el: any, itemKey: string) => {
	refInfo.value[itemKey] = el;
};

// 清空搜索框
const handlerResetBtn = () => {
	const keys = Object.keys(queryParams);
	for (const key of keys) {
		queryParams[key] = '';
	}
	const { tableData: newTableData, totalSize } = queryGroupData(
		ReportDefData?.GroupFieldCfg,
		ReportDefData?.MainGrpFieldCfg,
		groupsFields,
		mapFieldDataValid,
		levelDataValidArray
	);
	watch(
		() => totalSize.value,
		() => {
			pageConfig.total = totalSize.value;
			console.log('totalSize', totalSize.value);
			tableData.data = newTableData.data;
		}
	);
};

// 查询
const handlerSearchBtn = () => {
	const params = { ...queryParams, limit: 300, current: 1 };
	const { tableData: newTableData, totalSize } = queryGroupData(
		ReportDefData?.GroupFieldCfg,
		ReportDefData?.MainGrpFieldCfg,
		groupsFields,
		mapFieldDataValid,
		levelDataValidArray,
		params
	);
	watch(
		() => totalSize.value,
		() => {
			pageConfig.total = totalSize.value;
			console.log('totalSize', totalSize.value);
			tableData.data = newTableData.data;
		}
	);
};

const { handlerExportExcelBtn } = reportExportExcel(ReportDefData!, mainGrpFieldCfg, levelDataValidArray, tableData, levelNumber, otherFields);
</script>
<style lang="scss" scoped>
.pagination {
	margin-top: 20px;
}

.el-form.el-form--inline .el-form-item--large.el-form-item:last-of-type {
	margin-bottom: 0px !important;
}
.el-form-item {
	margin-bottom: 0;
}
</style>
